# -*- coding: utf-8 -*-

import os
import os.path
import sys
import user

ConfigDir = os.path.join(user.home, ".qapid")
ConfigFile = os.path.join(ConfigDir, "config")

DirOpenWith = False

if sys.platform == 'darwin':
	DirOpenWith = 'open -a finder.app'
elif sys.platform == 'win32':
	DirOpenWith = 'explorer.exe'
else:
	scanFor = ['dolphin', 'thunar', 'konqueror', 'nautilus'] #almost what I know
	for one in scanFor:
		if os.path.lexists('/usr/bin/' + one):
			DirOpenWith = one
			break

if os.path.isfile(ConfigDir):
	ofile=open(ConfigDir, "r")
	rfile=ofile.read()
	ofile.close()
	os.remove(ConfigDir)
	os.mkdir(ConfigDir)
	ofile=open(ConfigFile, "w")
	ofile.write(rfile)
	ofile.close()
	

if not os.path.lexists(ConfigDir):
	os.mkdir(ConfigDir)

if not os.path.lexists(ConfigFile):
	ofile = open(ConfigFile, "w")
	ofile.write("download_path=" + user.home + "\nshow_messages=yes\nshow_tray=yes\nrapidshare_username=\nrapidshare_password=\ncolumnsset=258:129:116:86:100")
	ofile.close()

def loadConf(name):
	if os.access(ConfigFile, os.R_OK):
		fConf = open(ConfigFile, "r")
		ConfData = fConf.read()
		fConf.close()
		ConfLines = ConfData.splitlines()
		for line in ConfLines:
			if line.startswith(name+'='):
				return line.split('=',1)[-1]

def saveConf(name, value):
	ConfLines = []
	if os.path.lexists(ConfigFile):
		if os.access(ConfigFile, os.W_OK):
			fConf = open(ConfigFile, "r")
			ConfData = fConf.read()
			fConf.close()
			ConfLines = ConfData.splitlines()
			i=0
			for line in ConfLines:
				if line.startswith(name+'='):
					ConfLines[i]=''
				i+=1

	ConfLines.append(name+'='+value)

	fConf = open(ConfigFile, "w")

	for line in ConfLines:
		if line:
			fConf.write(line+'\n')
	fConf.close()
 
